define(['jquery','jquerymobile','backend','utils'],function($,jqm,backend,utils) {
    console.log("model loaded");

    var LOAD_CURRENT_HOME_DATA_URL = '/environment/data.json';
    var LOAD_TEMPERATURE_DATA_URL = '/temperature/data.json';
    var LOAD_BRIGHTNESS_DATA_URL = '/brightness/data.json';
    var LOAD_FIRESAFETY_DATA_URL = '/firesafety/data.json';
    var LOAD_HOUSEWORK_BY_USER_URL = '/housework/data.json';
    var BLOODSUGAR_STATS_IN_TODAY_URL = '/bloodsugar/stats.json';
    var LOAD_BLOODSUGAR_HISTORY_BY_USER_URL = '/bloodsugar/data.json';
    var LOAD_USER_LIST_URL = '/user/data.json';
    var LOAD_ALL_USERS_LOCATION_TRACK_URL = '/locationtrack/now';
    var LOAD_LOCATION_TRACK_URL = '/locationtrack/:user';
    var LOAD_FILE_LIST_URL = '/myfiles/list';
    var LOAD_FILE_URL = '/myfiles/show';
    var LOAD_CONTACTS_URL = '/contactsync/sync';
    var LOAD_USER_OPTIONS_URL = '/options';
    var LOAD_MYSELF_INFO_URL = '/user/me';

    var UPDATE_HOUSEWORK_ITEM_URL = '/housework/update';
    var ADD_HOUSEWORK_ITEM_URL = '/housework/new';
    var ADD_BLOODSUGAR_ITEM_URL = '/bloodsugar/new';
    var DELETE_FILE_URL = '/myfiles/delete';
    var RENAME_FILE_URL = '/myfiles/rename';
    var ADD_NEW_FOLDER_URL = '/myfiles/folder/new';
    var MY_CONTACTS_BACKUP_URL = '/contactsync/backup';
    var ADD_NEW_LOCATION_URL = '/locationtrack/new';
    var UPDATE_USER_URL = '/user/edit';
    var USER_LOGIN_URL = '/user/login';
    var USER_ADD_URL = '/user/add';
    var USER_PASSWORD_EDIT_URL = '/user/password/edit';
    var USER_RESET_PASSWORD_URL = '/user/password/reset';
    var USER_DELETE_URL = '/user/delete';
    var UPDATE_OPTION_URL = '/option/edit';

    // Class CurrentHomeEnvironmentData Definition
    function CurrentHomeEnvironmentData() {
        this.temperature = 0;
        this.brightness = 1;
        this.firesafety = 1;
    }

    CurrentHomeEnvironmentData.prototype.load = function(callback) {
        backend.get(LOAD_CURRENT_HOME_DATA_URL, 
            {},
            function(data, status) {
               var dataList = [];

               if ('success' === status) {
                    var item = new CurrentHomeEnvironmentData();
                    var raw = JSON.parse(data);

                    item.temperature = raw[0].temperature;
                    item.brightness = raw[0].brightness;
                    item.firesafety = raw[0].firesafety;

                    dataList.push(item);
                    callback(dataList);
               }
               else {
                    utils.defaultBackendHandler();
               }
            },
            function() {
                utils.defaultBackendHandler();
            }
        );
    }
    // End of CurrentHomeEnvironmentData Definition

    // Class Housework Definition
    function Housework() {
        this.id = 0;
        this.user_id = 0;
        this.reward = '';
        this.task = '';
        this.status = 0;
        this.avatar = '';
        this.time = '';
        this.user_name = '';
    }

    Housework.prototype.load = function(user, callback) {
        backend.get(LOAD_HOUSEWORK_BY_USER_URL,
            {user: user},
            function(data, status) {
                var houseworkList = [];

                if ('success' === status) {
                   var rawList = JSON.parse(data);
                   
                   rawList.forEach(function(element, index, array) {
                        var housework = new Housework();
                        
                        housework.id = element.id;
                        housework.user_id = element.user_id;
                        housework.reward = element.reward;
                        housework.task = element.task;
                        housework.status = element.status;
                        housework.avatar = element.avatar;
                        housework.time = element.time;
                        housework.user_name = element.user_name;

                        houseworkList.push(housework);
                   });

                   callback(houseworkList);
                }
                else {
                    utils.defaultBackendHandler();
                }
            },

            function() {
                utils.defaultBackendHandler();
            }
        );
    }

    Housework.prototype.update = function(housework_id, callback) {
        backend.post(UPDATE_HOUSEWORK_ITEM_URL,
                     {id: housework_id},
                     function(data, status) {
                        if ('success' === status) {
                            var rawList = JSON.parse(data);

                            callback(rawList[0].resultCode);
                        }
                        else {
                            utils.defaultBackendHandler();
                        }
                     },

                     function() {
                        utils.defaultBackendHandler();
                     }
        );
    }

    Housework.prototype.add = function(user, task, reward, callback) {
        backend.post(ADD_HOUSEWORK_ITEM_URL,
                     {user: user, task: task, reward: reward},
                     function(data, status) {
                        if ('success' === status) {
                            var rawList = JSON.parse(data);

                            callback(rawList[0].resultCode);
                        }
                        else {
                            utils.defaultBackendHandler();
                        }
                     },
                     function() {
                        utils.defaultBackendHandler();
                     }
        ); 
    }
    // End of Housework Definition
    
    // Class User Definition
    function User() {
        this.id = null;
        this.sex = null;
        this.email = null;
        this.birth = null;
        this.name = null;
        this.avatar = null;
        this.role = null;
    }
    
    User.prototype.load = function(callback) {
        backend.get(LOAD_USER_LIST_URL, 
                    {},
                    function(data, status) {
                        var userList = [];

                        if ('success' === status) {
                            var rawList = JSON.parse(data);
                            
                            rawList.forEach(function(element, index, array) {
                                var user = new User();

                                user.id = element.id;
                                user.sex = element.sex;
                                user.email = element.email;
                                user.birth = element.birth;
                                user.name = element.name;
                                user.avatar = element.avatar;
                                user.role = element.role;

                                userList.push(user);
                            });
                            
                            callback(userList);
                        }
                        else {
                            utils.defaultBackendHandler();
                        }
                    },

                    function() {
                         utils.defaultBackendHandler();
                    }
                   );
    }

    User.prototype.update = function(fieldsToEditJson, callback) {
        backend.post(
                        UPDATE_USER_URL,
                        {new_fields_values_pairs: fieldsToEditJson},
                        function(data, status) {
                            if ('success' === status) {
                                var rawList = JSON.parse(data);
                                
                                callback(rawList[0].resultCode);
                            } else {
                                utils.defaultBackendHandler();
                            }
                        },
                        function() {
                            utils.defaultBackendHandler();
                        }
                    );
    };

    User.prototype.loadMe = function(callback) {
        backend.get(LOAD_MYSELF_INFO_URL,
                    {},
                    function(data, status) {
                        var dataList = [];

                        if ('success' === status) {
                            var rawList = JSON.parse(data);

                            rawList.forEach(function(element, index, array) {
                                var me = new User();

                                me.id = element.id;
                                me.name = element.name;
                                me.sex = element.sex;
                                me.birth = element.birth;
                                me.avatar = element.avatar;
                                me.email = element.email;
                                me.role = element.role;

                                dataList.push(element);
                            });
                        }
                        else {
                            utils.defaultBackendHandler();
                        }
                        callback(dataList);
                    },
                    function() {
                        utils.defaultBackendHandler();
                    }
        );

    };

    User.prototype.editPassword = function (currentPassword, newPassword, callback) {
        backend.post(
                        USER_PASSWORD_EDIT_URL,
                        {
                            current_password: currentPassword,
                            new_password:     newPassword,
                        },
                        function(data, status) {
                            if ('success' === status) {
                                var rawList = JSON.parse(data);

                                callback(rawList[0].resultCode);
                            }
                            else {
                                utils.defaultBackendHandler();
                            }
                        },
                        function() {
                            utils.defaultBackendHandler();
                        }
                    );
    };

    User.prototype.login = function(username, password, callback) {
        backend.post(
                        USER_LOGIN_URL,
                        {username: username, password: password},
                        function(data, status) {
                            if ('success' === status) {
                                var rawList = JSON.parse(data);

                                callback(rawList[0]);
                            }
                            else {
                                utils.defaultBackendHandler();
                            }
                        },
                        function () {
                            utils.defaultBackendHandler();
                        }
                    );
    };

    User.prototype.add = function(username, role, callback) {
        backend.post(
                        USER_ADD_URL,
                        {username: username, role: role},
                        function(data, status) {
                            if ('success' === status) {
                                var rawList = JSON.parse(data);

                                callback(rawList[0]);
                            }
                            else {
                                utils.defaultBackendHandler();
                            }
                        },
                        function () {
                            utils.defaultBackendHandler();
                        }
                    );
    };

    User.prototype.remove = function(id, callback) {
        backend.post(
                        USER_DELETE_URL,
                        {id: id},
                        function(data, status) {
                            if ('success' === status) {
                                var rawList = JSON.parse(data);

                                callback(rawList[0].resultCode);
                            }
                            else {
                                utils.defaultBackendHandler();
                            }
                        },
                        function() {
                            utils.defaultBackendHandler();
                        }
                    );
    };

    User.prototype.resetPassword = function(id, callback) {
        backend.post(
                        USER_RESET_PASSWORD_URL,
                        {id: id},
                        function(data, status) {
                            if ('success' === status) {
                                var rawList = JSON.parse(data);

                                callback(rawList[0].resultCode);
                            }
                            else {
                                utils.defaultBackendHandler();
                            }
                        },
                        function() {
                            utils.defaultBackendHandler();
                        }
                    );
    };

    // End of User Definition

    // Class Temperature Definition
    function Temperature() {
        this.id = 0;
        this.time = "";
        this.value = 0.0;
    }

    Temperature.prototype.load = function(type, callback) {
        backend.get(LOAD_TEMPERATURE_DATA_URL,
                    {view: type},
                    function(data, status) {
                        var temperatureList = [];

                        if ('success' === status) {
                            var rawList = JSON.parse(data);

                            if (type === "raw") {
                                rawList.forEach(function(element, index, array) {
                                    //...TODO
                                }
                                );
                            }
                            else if (type === "graph") {
                                temperatureList.push(rawList[0]);
                            }
                        }
                        else {
                            utils.defaultBackendHandler();
                        }

                        callback(temperatureList);
                    },

                    function() {
                        utils.defaultBackendHandler();
                    }
        ); 
    }
    // End of Temperature Definition
    
    // Class AlertRecord Definition
    function AlertRecord() {
        this.id = 0;
        this.type = 0;
        this.time = '';
    }

    AlertRecord.prototype.load = function(type, callback) {
        backend.get(type == 1 ? LOAD_BRIGHTNESS_DATA_URL : LOAD_FIRESAFETY_DATA_URL,
                    {},
                    function(data, status) {
                        var dataList = [];

                        if ('success' === status) {
                            var rawList = JSON.parse(data);

                            rawList.forEach(function(element, index, array) {
                                var record = new AlertRecord();

                                record.id = element.id;
                                record.type = element.type;
                                record.time = element.time;

                                dataList.push(record);
                            });
                        }
                        else {
                            utils.defaultBackendHandler();
                        }

                        callback(dataList);
                    },
                    function() {
                        utils.defaultBackendHandler();
                    }
        );
    }
    // End of AlertRecord Definition
     
    // Class BloodSugar Definition 
    function BloodSugar() {
        this.time = '';
        this.tag = '';
        this.id = 0;
        this.value = 0.0;
        this.user_id = 0;
        this.date = '';
    }

    BloodSugar.prototype.load = function(callback) {
        backend.get(LOAD_BLOODSUGAR_HISTORY_BY_USER_URL,
                    {},
                    function(data, status) {
                        var dataList = [];

                        if ('success' === status) {
                            var rawList = JSON.parse(data);

                            rawList.forEach(function(element, index, array) {
                                var sugar = new BloodSugar();

                                sugar.time = element.time;
                                sugar.tag = element.tag;
                                sugar.id = element.id;
                                sugar.value = element.value;
                                sugar.user_id = element.user_id;
                                sugar.date = element.date;

                                dataList.push(sugar);
                            });

                            callback(dataList);
                        }
                        else {
                            utils.defaultBackendHandler();
                        }
                    },
                    function() {
                        utils.defaultBackendHandler();
                    }
        );
    };

    BloodSugar.prototype.statsInToday = function(callback) {
        backend.get(BLOODSUGAR_STATS_IN_TODAY_URL,
                    {},
                    function(data, status) {
                        var dataList = [];

                        if ('success' === status) {
                            var rawList = JSON.parse(data);

                            dataList.push(rawList[0]);
                        }
                        else {
                            utils.defaultBackendHandler();
                        }

                        callback(dataList);
                    },
                    function() {
                        utils.defaultBackendHandler();
                    }
        );
    };

    BloodSugar.prototype.create = function(date, time, tag, value, callback) {
        backend.post(ADD_BLOODSUGAR_ITEM_URL,
                    {
                        date: date,
                        time: time,
                        tag: tag,
                        value: value,
                    },
                    function(data, status) {
                        if ('success' === status) {
                            var rawList = JSON.parse(data);

                            callback(rawList[0].resultCode);
                        }
                        else {
                            utils.defaultBackendHandler();
                        }
                    },
                    function() {
                        utils.defaultBackendHandler();
                    }
        );
    };
    // End of BloodSugar Definition
     
    // Class LocationTrack Definition
    function LocationTrack() {
        this.id = 0;
        this.time = '';
        this.user_id = 0;
        this.location_desc = '';
        this.user_name = '';
        this.user_avatar = '';
    }

    LocationTrack.prototype.allUsersRecords = function(callback) {
        backend.get(LOAD_ALL_USERS_LOCATION_TRACK_URL,
                    {},
                    function(data, status) {
                        var dataList = [];

                        if ('success' === status) {
                            var rawList = JSON.parse(data);

                            rawList.forEach(function(element, index, array) {
                                var locationRecord = new LocationTrack();
                                
                                locationRecord.id = element.id;
                                locationRecord.time = element.time;
                                locationRecord.user_id = element.user_id;
                                locationRecord.location_desc = element.location_desc;
                                locationRecord.user_name = element.user_name;
                                locationRecord.user_avatar = element.user_avatar;

                                dataList.push(locationRecord);
                            });
                        }
                        else {
                            utils.defaultBackendHandler();
                        }

                        callback(dataList);
                    },
                    function() {
                        utils.defaultBackendHandler();
                    }
                    );
    };

    LocationTrack.prototype.load = function(user_id, callback) {
        backend.get(LOAD_LOCATION_TRACK_URL.replace(":user", user_id),
                    {},
                    function(data, status) {
                        var dataList = [];

                        if ('success' === status) {
                            var rawList = JSON.parse(data);

                            rawList.forEach(function(element, index, array) {
                                var locationRecord = new LocationTrack();

                                locationRecord.id = element.id;
                                locationRecord.time = element.time;
                                locationRecord.user_id = element.user_id;
                                locationRecord.location_desc = element.location_desc;

                                dataList.push(locationRecord);
                            });
                        }
                        else {
                            utils.defaultBackendHandler();
                        }

                        callback(dataList);
                    },
                    function() {
                        utils.defaultBackendHandler();
                    }
                    );
    };

    LocationTrack.prototype.add = function(isLivingInChina, geolocation, callback) {
        backend.post(ADD_NEW_LOCATION_URL,
                     {
                         is_living_in_china: isLivingInChina,
                         geolocation: geolocation,
                     },
                     function(data, status) {
                        if ('success' === status) {
                            var rawList = JSON.parse(data);
                            
                            callback(rawList[0].resultCode);
                        }
                        else {
                            utils.defaultBackendHandler();
                        }
                     },
                     function() {
                        utils.defaultBackendHandler();
                     }
                    );
    };
    // End of LocationTrack Definition 

    // Class MyFile Definition
    function MyFile() {
        this.name = '';
        this.type = 1;
    }

    MyFile.prototype.loadList = function(path, callback) {
        backend.get(LOAD_FILE_LIST_URL,
                    {path: path},
                    function(data, status) {
                        var dataList = [];
                        
                        if ('success' === status) {
                            var rawList = JSON.parse(data);

                            rawList.forEach(function(element, index, array) {
                               var file = new MyFile();

                               file.name = element.name;
                               file.type = element.type;

                               dataList.push(file);
                            });
                        }
                        else {
                            utils.defaultBackendHandler();
                        }

                        callback(dataList);
                    },
                    function() {
                        utils.defaultBackendHandler();
                    }
                    );
    };

    MyFile.prototype.newFolder = function(path, folderName, callback) {
        backend.post(ADD_NEW_FOLDER_URL,
                    {
                        path: path,
                        name: folderName,
                    },
                    function(data, status) {
                        if ('success' === status) {
                            var rawList = JSON.parse(data);

                            callback(rawList[0].resultCode);
                        }
                        else {
                            utils.defaultBackendHandler();
                        }
                    },
                    function() {
                        utils.defaultBackendHandler();
                    }
                    );
    };

    MyFile.prototype.remove = function(path, callback) {
        backend.post(
                        DELETE_FILE_URL,
                        {path: path},
                        function(data, status) {
                            if ('success' === status) {
                                var rawList = JSON.parse(data);

                                callback(rawList[0].resultCode);
                            }
                            else {
                                utils.defaultBackendHandler();
                            }
                        },
                        function() {
                            utils.defaultBackendHandler();
                        }
                    );
    };

    MyFile.prototype.rename = function(oriPath, newPath, callback) {
        backend.post(
                        RENAME_FILE_URL,
                        {
                            ori_path: oriPath,
                            new_path: newPath
                        },
                        function(data, status) {
                            if ('success' === status) {
                                var rawList = JSON.parse(data);

                                callback(rawList[0].resultCode);
                            }
                            else {
                                utils.defaultBackendHandler();
                            }
                        },
                        function() {
                            utils.defaultBackendHandler();
                        }
                    );
    };

    // End of MyFile Definition

    // Class MyContact Definition
    function MyContact() {
        this.id = 0;
        this.user_id = 0;
        this.contacts = '';
    }

    MyContact.prototype.backup = function(contacts, callback) {
        backend.post(
                        MY_CONTACTS_BACKUP_URL,
                        {"contacts.json": contacts},
                        function(data, status) {
                            if ('success' === status) {
                                var rawList = JSON.parse(data);

                                callback(rawList[0].resultCode);
                            }
                            else {
                                utils.defaultBackendHandler();
                            }
                        },
                        function() {
                            utils.defaultBackendHandler();
                        }
        );
    };

    MyContact.prototype.load = function(callback) {
        backend.get(
                        LOAD_CONTACTS_URL,
                        {},
                        function(data, status) {
                            var dataList = [];

                            if ('success' === status) {
                                var rawList = JSON.parse(data);
                                
                                rawList.forEach(function(element, index, array) {
                                    var contact = new MyContact();

                                    contact.contacts = element.contacts;

                                    dataList.push(contact);
                                });
                                
                                callback(dataList);
                            }
                            else {
                                utils.defaultBackendHandler();
                            }
                        },
                        function() {
                            utils.defaultBackendHandler();
                        }
        );
    };
    // End of MyContact Definition

    // Class Option Definition
    function Option() {
        this.id = null;
        this.key = null;
        this.value = null;
        this.userId = null;
    }

    Option.prototype.update = function(key, value, callback) {
        backend.post(UPDATE_OPTION_URL,
                     {key: key, value: value},
                     function(data, status) {
                        if ('success' === status) {
                            var rawList = JSON.parse(data);

                            callback(rawList[0].resultCode);
                        }
                        else {
                            utils.defaultBackendHandler();
                        }
                     },
                     function() {
                        utils.defaultBackendHandler();
                     }
        );
    };

    Option.prototype.load = function(callback) {
        backend.get(LOAD_USER_OPTIONS_URL,
                    {},
                    function(data, status) {
                        var dataList = [];

                        if ('success' === status) {
                            var rawList = JSON.parse(data);

                            rawList.forEach(function(element, index, array) {
                                var option = new Option();

                                option.id = element.id;
                                option.key = element.key;
                                option.value = element.value;
                                option.userId = element.user_id;

                                dataList.push(option);
                            });
                        }
                        else {
                            utils.defaultBackendHandler();
                        }

                        callback(dataList);
                    },
                    function() {
                        utils.defaultBackendHandler();
                    }
        );
    };
    // End of Option Definition

    return {
        CurrentHomeEnvironmentData: CurrentHomeEnvironmentData,
        Housework: Housework,
        User: User,
        Temperature: Temperature,
        AlertRecord: AlertRecord,
        BloodSugar: BloodSugar,
        LocationTrack: LocationTrack,
        MyFile: MyFile,
        MyContact: MyContact,
        Option: Option,
    };
});
